//
//  CollectionViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/29.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "CollectionViewController.h"
#import "DateBaseManager.h"
#import "VideoCollectionCell.h"
#import "AllDetailModel.h"
#import <UIImageView+WebCache.h>
#import "NewsDataBaseManager.h"
#import "Videomodel.h"
#import "TitlesModel.h"
#import "TitlesCell.h"
#import "TitleViewController.h"
#import "NewsCollectionCell.h"
#import "PushWebViewVC.h"
#import "TitleDataBaseManager.h"
#import "AfNetWorkingHandler.h"
#import "VideoDetaileViewController.h"
@interface CollectionViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UITableView *newsTableView;
@property (nonatomic, retain)UITableView *titleTableView;
@property (nonatomic, retain)NSMutableArray *dataArr;//视频数组
@property (nonatomic, retain)NSMutableArray *newsArr;//新闻数组
@property (nonatomic, retain)NSMutableArray *titleArr;//话题数组
@property (nonatomic, retain)UIScrollView *scroll;//大的scroll
@property (nonatomic, retain)UIView *blank;//按钮栏
@property (nonatomic, retain)UIButton *videoBtn;//视频按钮
@property (nonatomic, retain)UIButton *newsBtn;//新闻按钮
@property (nonatomic, retain)UISegmentedControl *seg;
@end

@implementation CollectionViewController
-(void)dealloc
{
    [_tableView release];
    [_newsTableView release];
    [_titleTableView release];
    [_dataArr release];
    [_newsArr release];
    [_titleArr release];
    [_scroll release];
    [_blank release];
    [_videoBtn release];
    [_newsBtn release];
    [_seg release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"收藏";
    //设置编辑按钮
    UIButton *edit = [UIButton buttonWithType:UIButtonTypeSystem];
    [edit setTitle:@"编辑" forState:UIControlStateNormal];
    [edit setTitle:@"完成" forState:UIControlStateSelected];
     edit.frame = CGRectMake(0, 0, 50, 50);
    [edit addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:edit]autorelease];
    //上面的按钮栏
    self.blank = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40)];
//    _blank.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_blank];
    [_blank release];
    //用segment创建按钮
    self.seg = [[UISegmentedControl alloc]initWithItems:@[@"视频", @"新闻", @"专题"]];
    _seg.frame = _blank.frame;
    _seg.selectedSegmentIndex = 0;
    _seg.tintColor = [UIColor grayColor];
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_seg];
    [_seg release];
    //scrollView各收藏分类
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _blank.frame.origin.y + _blank.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
//    _scroll.backgroundColor = [UIColor yellowColor];
    _scroll.contentSize = CGSizeMake(3 * self.view.frame.size.width, self.view.frame.size.height);
    _scroll.bounces = NO;
    _scroll.pagingEnabled = YES;
    _scroll.delegate = self;
//    _scroll.scrollEnabled = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:_scroll];
    [_scroll release];
    //视频页
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0 , self.view.frame.size.width, _scroll.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource= self;
//    _tableView.backgroundColor = [UIColor yellowColor];
    [_tableView registerClass:[VideoCollectionCell class] forCellReuseIdentifier:@"collectonCell"];
    [_scroll addSubview:_tableView];
    [_tableView release];
    //新闻页
    self.newsTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, _scroll.frame.size.height)];
    _newsTableView.delegate = self;
    _newsTableView.dataSource= self;
//    _newsTableView.backgroundColor = [UIColor redColor];
    [_newsTableView registerClass:[NewsCollectionCell class] forCellReuseIdentifier:@"newsCell"];
    [_scroll addSubview:_newsTableView];
    [_newsTableView release];
    //专题页
    self.titleTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, _scroll.frame.size.height)];
    _titleTableView.delegate = self;
    _titleTableView.dataSource= self;
//    _titleTableView.backgroundColor = [UIColor greenColor];
    [_titleTableView registerClass:[TitlesCell class] forCellReuseIdentifier:@"titlesCell"];
    [_scroll addSubview:_titleTableView];
    [_titleTableView release];
    //从数据库中获取数据
    [[DateBaseManager shareInstance]openDB];
    self.dataArr = [[DateBaseManager shareInstance]select];
    //从新闻数据库中获取数据
    [[NewsDataBaseManager shareInstance]openDB];
    self.newsArr = [[NewsDataBaseManager shareInstance]select];
    //从话题数据库中获取数据
    [[TitleDataBaseManager shareInstance]openDB];
    self.titleArr = [[TitleDataBaseManager shareInstance]select];
    //页面下面添加偏移量
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    self.newsTableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    self.titleTableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
}
//滑动时让segment跟随动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x < self.view.frame.size.width) {
        _seg.selectedSegmentIndex = 0;
    }else if (scrollView.contentOffset.x < self.view.frame.size.width * 2) {
        _seg.selectedSegmentIndex = 1;
    }else{
        _seg.selectedSegmentIndex = 2;
    }
}
//segment的点击方法
-(void)segAction:(UISegmentedControl *)seg
{
    NSInteger i = seg.selectedSegmentIndex;
    if (i == 0) {
         _scroll.contentOffset = CGPointMake(0,0);
    }
    if (i == 1) {
        _scroll.contentOffset = CGPointMake(self.view.frame.size.width,0);
    }
    if (i == 2) {
        _scroll.contentOffset = CGPointMake(self.view.frame.size.width * 2,0);
    }
}
//点击按钮偏移量跳到对应的页面
-(void)videoAction
{
    _videoBtn.frame = CGRectMake(self.view.frame.size.width / 4, 5, self.view.frame.size.width / 7, 25);
    //设置按钮的中心位置
    _videoBtn.center = CGPointMake(self.view.frame.size.width / 3,  self.blank.frame.size.height / 2);
    _videoBtn.backgroundColor = [UIColor redColor];
    _scroll.contentOffset = CGPointMake(0,0);
}
-(void)newsAction
{
    _scroll.contentOffset = CGPointMake(self.view.frame.size.width,0);
}
//tableView是否允许编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//编辑按钮触发的方法
-(void)editAction:(UIButton *)btn
{
    btn.selected = !btn.selected;
    [_tableView setEditing:btn.selected animated:YES];
    [_newsTableView setEditing:btn.selected animated:YES];
    [_titleTableView setEditing:btn.selected animated:YES];
}
//根据按钮的状态 设置tableView是否处于编辑状态
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
    [_newsTableView setEditing:editing animated:YES];
    [_titleTableView setEditing:editing animated:YES];
}
//通过tableView的编辑状态 判断执行什么操作
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //执行数据库删除
        if ([tableView isEqual:_tableView]) {
            //视频页
            Videomodel *m = _dataArr[indexPath.row];
            [[DateBaseManager shareInstance]deleteVideoWithId:m.videoId];
            //从当前的数据数组中移除
            [_dataArr removeObjectAtIndex:indexPath.row];
            //视图同步
            [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        if ([tableView isEqual:_newsTableView]) {
            //新闻页
            AllDetailModel *newsM = _newsArr[indexPath.row];
            [[NewsDataBaseManager shareInstance]deleteNewsWithId: newsM.NewsId];
            //从当前页面的数组中删除
            [_newsArr removeObjectAtIndex:indexPath.row];
            //视图同步
            [_newsTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        if ([tableView isEqual:_titleTableView]) {
            //话题页
            TitlesModel *titleM = _titleArr[indexPath.row];
            [[TitleDataBaseManager shareInstance]deleteTitlesWithId:titleM.titleId];
            //从当前页面的数组中删除
            [_titleArr removeObjectAtIndex:indexPath.row];
            //视图同步
            [_titleTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        
    }
}
//页面创建cell的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_tableView]) {
        return _dataArr.count;
    }
    if ([tableView isEqual:_newsTableView]) {
        return _newsArr.count;
    }
    if ([tableView isEqual:_titleTableView]) {
        return _titleArr.count;
    }else{
        return 0;
    }
}
//cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_titleTableView]) {
        return 320;
    }
    if ([tableView isEqual:_tableView]) {
        return self.view.frame.size.height / 5;
    }
    else{
    return self.view.frame.size.height / 5;
    }
}
//点击进入详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_newsTableView]) {
        PushWebViewVC *newsVC = [[PushWebViewVC alloc]init];
        AllDetailModel *m = _newsArr[indexPath.row];
        newsVC.pathstr = m.weburl;
        newsVC.model = m;
        [self.navigationController pushViewController:newsVC animated:YES];
        [newsVC release];
    }
    //视频详情页
    if ([tableView isEqual:_tableView]) {
        Videomodel *m = _dataArr[indexPath.row];
        NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/detail/%@.html", m.vid];
        [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
            //
            NSString *path = result[@"vurl"];
            VideoDetaileViewController *vc = [[VideoDetaileViewController alloc]init];
//            PushWebViewVC *vc = [[PushWebViewVC alloc]init];
            vc.pathstr = path;
            vc.model = m;
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }];
    }
    //专题页
    if ([tableView isEqual:_titleTableView]) {
        TitleViewController *titleVC = [[TitleViewController alloc]init];
        TitlesModel *m = _titleArr[indexPath.row];
        titleVC.model = m;
        [self.navigationController pushViewController:titleVC animated:YES];
        [titleVC release];
    }
}
//设置每个cell的详情
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        VideoCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectonCell" forIndexPath:indexPath];
        if (_dataArr.count != 0) {
            Videomodel *m = _dataArr[indexPath.row];
            cell.titleLable.text = m.title;
            
            //将时间转换成00:00形式
            NSNumber *n = m.length;
            if (n.integerValue < 60) {
                cell.timeLable.text = [NSString stringWithFormat:@"00: %ld", n.integerValue];
            }else{
                NSInteger fen = n.integerValue / 60;
                NSInteger miao = n.integerValue - 60 * fen;
                NSString *time = [NSString stringWithFormat:@"%ld分%ld秒", fen, miao];
                cell.timeLable.text = time;
            }
            cell.replyLable.text = [m.replyCount.stringValue stringByAppendingString:@"评论"];
            [cell.picture sd_setImageWithURL:[NSURL URLWithString:m.cover]];
        }
        return cell;

    }
    if ([tableView isEqual:_newsTableView]) {
        NewsCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell"];
        AllDetailModel *m = _newsArr[indexPath.row];
        cell.contentLable.text = m.title;
        cell.writerLable.text = m.auther_name;
        cell.timeLable.text = m.date;
        return cell;
    }if ([tableView isEqual:_titleTableView]) {
        TitlesModel *m = _titleArr[indexPath.row];
        TitlesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"titlesCell" forIndexPath:indexPath];
        cell.nameLable.text = m.name;
        cell.jieshaoLable.text = m.alias;
        [cell.img sd_setImageWithURL:[NSURL URLWithString:m.picurl]];
        [cell.photo sd_setImageWithURL:[NSURL URLWithString:m.headpicurl]];
        cell.contentsLable.font = [UIFont systemFontOfSize:14];
        cell.contentsLable.text = [[m.concernCount.stringValue stringByAppendingString:@"关注"] stringByAppendingString:@" |"] ;
        cell.kindLable.text = m.classification;
        cell.model = m;

        return cell;
    }
    else{
        return 0;
    }
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
